# -*- coding: utf-8 -*-
import pathlib
from urllib.parse import unquote, urljoin

import httpx

from .constants import api_token, GATEWAY_BASE

client = httpx.Client()


def download(url, path, **kwargs):
    name = pathlib.Path(path, pathlib.Path(url).name)

    with open(name, "wb") as fout:
        with client.stream('GET', unquote(url), **kwargs) as response:
            for chunk in response.iter_bytes():
                fout.write(chunk)


def fetch(uri=None, **kwargs):
    kwargs['params'] = {'access_token': api_token}
    url = urljoin(GATEWAY_BASE, uri)
    response = client.get(url=url, **kwargs)

    return response

# async def async_download(url, name):
#     async with httpx.AsyncClient() as child:
#         with open(name, "wb") as fout:
#             async with child.stream('GET', url) as response:
#                 async for chunk in response.aiter_bytes():
#                     fout.write(chunk)
#
#
# def async_fetch(uri=None, **kwargs):
#     kwargs['params'] = {'access_token': api_token}
#
#     url = urljoin(GATEWAY_BASE, uri)
#
#     logger.warning(url)
#
#     async with httpx.AsyncClient() as child:
#         async with child.get(url=url, **kwargs) as response:
#             return response
